import * as API from '@/constants/api'
import { filterNumber, scientificToNumber } from '@/utils/number'

import { GET_INIT_INFO, UPDATE_EXCHANGE_MARKET, UPDATE_TODAY_NOTICE } from '@/constants/mutation-types'
import { coinPairInfoStorage } from '@/utils/storage'
import { updateUpAndDownRank, usdPrice } from '@/utils/market'

export const state = () => ({
  usd2cny: 0,
  coinPairInfo: coinPairInfoStorage.get() || {},
  moneyList: [],

  realTimeQuotes: {},
  // 币对美元汇率
  coin2usd: {},

  // 涨跌幅
  upRank: [],
  downRank: []
})

export const getters = {
  // group by symbol
  realTimeQuotesBySymbol: (state) => {
    const data = {}
    Object.keys(state.realTimeQuotes).forEach((name) => {
      if (!(state.realTimeQuotes[name].open > 0)) {
        return
      }
      const info = state.coinPairInfo[name]
      if (!data[info.money]) {
        data[info.money] = {}
      }
      data[info.money][name] = state.realTimeQuotes[name]
    })
    return data
  },
  realTimeQuotesByType (state) {
    const data = {
      self: {}
    }
    Object.keys(state.coinPairInfo).forEach((symbol) => {
      const item = state.coinPairInfo[symbol]
      const realTimeItem = state.realTimeQuotes[symbol]
      if (realTimeItem && realTimeItem.open > 0) {
        if (item.status === 1) {
          // 自选
          data.self[symbol] = realTimeItem
        }
      }
    })
    return data
  },
  coinPair (state, _, { exchange }) {
    const { coinPairInfo } = state
    const coinPair = coinPairInfo[exchange.symbol]
    let precision
    if (coinPair.decimals > 8) {
      precision = 8
    } else {
      precision = Math.ceil(coinPair.decimals / 1)
    }
    coinPair.interval = scientificToNumber(1 / 10 ** precision)
    return coinPair
  },
  // group by money
  coinPairInfoByMoney (state) {
    const data = {}
    Object.keys(state.coinPairInfo).forEach((symbol) => {
      const info = state.coinPairInfo[symbol]
      if (!data[info.money]) {
        data[info.money] = {}
      }
      data[info.money][symbol] = info
    })
    return data
  },
  // 折现率
  discountRate (state, _, { exchange }) {
    const {
      realTimeQuotes,
      coinPairInfo
    } = state
    if (realTimeQuotes[exchange.symbol] && coinPairInfo[exchange.symbol]) {
      if (coinPairInfo[exchange.symbol].money === 'USDT') {
        return 1
      }
      const baseSymbol = coinPairInfo[exchange.symbol].money + 'USDT'
      if (realTimeQuotes[baseSymbol]) {
        const usdtPair = realTimeQuotes[baseSymbol]
        const num2 = filterNumber(usdtPair.last)
        return num2
      }
    }
    return 0
  },
  getOhlcBySymbol: state => (symbol) => {
    return state.realTimeQuotes[symbol]
  }
}
export const mutations = {
  [GET_INIT_INFO] (state, rate) {
    state.usd2cny = rate
  },
  [UPDATE_EXCHANGE_MARKET] (state, {
    coinPairData,
    moneyList
  }) {
    state.coinPairInfo = coinPairData
    if (moneyList) {
      state.moneyList = moneyList
    }
  },
  [UPDATE_TODAY_NOTICE] (state, { params }) {
    const [name, data] = params
    state.realTimeQuotes = {
      ...state.realTimeQuotes,
      [name]: data
    }
    state.coin2usd = {
      ...state.coin2usd,
      [name]: usdPrice(name, 'last', state)
    }
    if (data.open > 0) {
      updateUpAndDownRank(state, params)
    }
  }
}

export const actions = {
  async getCoinPairInfo ({ commit }, params) {
    const { data } = await this.$axios.$post(API.GET_COIN_PAIR_INFO, params)
    const coinPairData = {}
    const moneyList = []
    data.forEach((item) => {
      moneyList.push(item.main)
      item.list.forEach((v) => {
        coinPairData[v.name] = v
      })
    })
    console.log('#############');
    console.log(moneyList);
    coinPairInfoStorage.set(coinPairData)
    commit(UPDATE_EXCHANGE_MARKET, {
      coinPairData,
      moneyList
    })
    // 订阅
    this.$socket.subscribeToday(coinPairData)
  },
  async addSelf ({ commit }, params) {
    await this.$axios.$post(API.ADD_SELF, params)
    const {
      stock,
      money
    } = params
    const symbol = `${stock}${money}`
    const coinPairData = coinPairInfoStorage.get()
    const item = coinPairData[symbol]
    item.status = 1
    coinPairData[symbol] = item
    coinPairInfoStorage.set(coinPairData)
    commit(UPDATE_EXCHANGE_MARKET, { coinPairData })
  },
  async cancelSelf ({ commit }, params) {
    await this.$axios.$post(API.CANCEL_SELF, params)
    const {
      stock,
      money
    } = params
    const symbol = `${stock}${money}`
    const coinPairData = coinPairInfoStorage.get()
    const item = coinPairData[symbol]
    item.status = 0
    coinPairData[symbol] = item
    coinPairInfoStorage.set(coinPairData)
    commit(UPDATE_EXCHANGE_MARKET, { coinPairData })
  }
}
